<template
  ><!---->
  <Modal
    v-model="modal.show"
    :title="modal.title"
    :width="920"
    :loading="modal.loading"
    :mask-closable="false"
    @on-cancel="closeModal"
    footer-hide
  >
    <!-- @on-ok="confirmSelect"-->
    <Row style="margin-bottom:10px;" v-if="modal.show">
      团队 ： <Tag color="blue">{{ group.name }}</Tag>
      <div style="float:right;">
        实验组 ：
        <Select filterable
          v-model="expGroupId"
          placeholder="请选择实验组"
          @on-change="changeGroup"
          :not-found-text="loadingGroup ? '加载中...' : '无匹配数据'"
          label-in-value
          filterable
          class="experimental-group"
        >
          <Option
            v-for="group in expGroupList"
            :title="group.name"
            :value="group.id"
            :key="group.id"
            :label="group.name"
            >{{ group.name }}</Option
          >
        </Select>
      </div>
    </Row>
    <Row v-if="selectedUsers.length > 0" style="margin:10px 0;">
      已添加成员：
      <div style="display: flex; flex-wrap: wrap;">
        <Tag
          type="border"
          closable
          color="primary"
          v-for="user in selectedUsers"
          :key="user.userId"
          @on-close="removeUser(user.userId)"
          :name="user.userId"
          >{{ user.userName || user.user.nickname }}</Tag
        >
        <Button type="error" @click="clearUsers" size="small">清空用户</Button>
      </div>
    </Row>
    <Transfer
      :data="formatallSelectUsers"
      :list-style="listStyle"
      :target-keys="formatSelectedUsers"
      :render-format="render2"
      :filter-method="filterMethod"
      :operations="['移除', '接入']"
      filter-placeholder="请输入用户名、昵称搜索"
      :titles="['实验组未选用户', '实验组已选用户']"
      filterable
      @on-change="handleChange"
    ></Transfer>
  </Modal>
</template>

<script>
import { getexpergrouplist, getexpergroupusers, getAllRanges } from '@/api/access_new';
export default {
  name: 'AccessTransfer',
  props: {
    value: {
      //显示、隐藏
      type: Boolean,
      default: false
    },
    group: {
      //组信息
      type: Object,
      default: () => {
        return {
          name: '',
          userList: []
        };
      }
    },
    allSelectedUsers: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      modal: {
        show: this.value,
        title: '添加成员',
        loading: true,
        width: 500
      },
      listStyle: {
        width: '45%',
        height: '300px'
      },
      allUsers: [], //接口获取的组成员数据
      expGroupList: [],
      selectedUsers: [],
      expGroupId: '',
      loadingGroup: false
    };
  },
  filters: {},
  watch: {
    'modal.show': function(val) {
      if (!val) {
        this.$emit('input', false);
        this.$emit('close', this.selectedUsers);
      }
    },
    value(val) {
      val ? this.showModal() : this.closeModal();
    },
    'group.userList': function(val) {
      this.selectedUsers = this.group.userList;
    }
  },
  mounted() {
    this.selectedUsers = this.group.userList;
  },
  computed: {
    formatSelectedUsers() {
      // 选中的用户的id列表
      return this.selectedUsers.map((user) => user.userId);
    },
    formatallSelectUsers() {
      //当前可选的用户列表
      let arr = this.allSelectedUsers.map((user) => user.userId); // 所有已经加入的用户
      let arr2 = this.selectedUsers.map((user) => user.userId); // 本团队已经选择的用户
      let arr3 = arr.filter((id) => !arr2.includes(id)); // 加入其他团队的用户
      let cArr = this.allUsers
        .filter((user) => {
          // 获取实验员身份的人
          if (user.user) {
            return user.user.type == 'experimenter';
          } else {
            return user;
          }
        })
        .filter((user) => !arr3.includes(user.userId)); // 过滤掉加入其他团队的成员，本团队的成员虽然已加入，还是再要穿梭框中展示
      return cArr.map((user) => {
        return {
          key: user.userId,
          label: user.label,
          des: user.expGroupName,
          rangeId: user.user.rangeId
          // disabled:this.selectedUsers.length >= this.group.userCount && !this.selectedUsers.find(item => item.userId === user.userId)
        };
      });
    }
  },
  methods: {
    showModal() {
      this.modal.show = true;
      this.getAllRanges();
    },
    closeModal() {
      this.group.userList = this.selectedUsers;
      this.modal.show = false;
    },
    //查询所有靶场
    getAllRanges() {
      this.loadingRange = true;
      getAllRanges()
        .then((res) => {
          if (res.code == 1) {
            this.rangeList = res.data;
            if (this.isDistributed != 1) {
              let selfRange = {};
              this.selfRange = this.rangeList.find((item) => {
                if (item.self == '0') {
                  return item;
                }
              });
              this.rangeList = [];
              this.rangeList.push(this.selfRange);
            }
            this.rangeId = this.rangeList[0].id;
            this.getExpGroupList(this.rangeId);
          } else {
            this.$Message.warning('查询靶场失败');
          }
        })
        .finally(() => {
          this.loadingRange = false;
        });
    },
    // 获取可使用的用户组列表
    getExpGroupList(rangeId) {
      this.loadingGroup = true;
      let params = {
        pageIndex: 1,
        pageSize: 2147483646,
        rangeId: rangeId
      };
      // if(this.type==0){
      // 	params.self=true
      // }
      getexpergrouplist(params)
        .then((data) => {
          if (data.code == 1) {
            this.expGroupList = data.data.items.filter((item) => item.userCount > 0);
            if (this.expGroupList.length) {
              this.expGroupId = this.expGroupList[0].id;
              this.getExpGroupUsers(this.expGroupList[0]);
            }
          }
        })
        .finally(() => {
          this.loadingGroup = false;
        });
    },
    // 选择实验组，级联查询组成员
    changeGroup(group) {
      if(group && group.value){
        let expGroup = {
          name: group.label,
          id: group.value
        };
        this.getExpGroupUsers(expGroup);
      }
    },
    // 获取用户组内的成员列表
    getExpGroupUsers(group) {
      return new Promise((resolve, reject) => {
        getexpergroupusers(group.id).then((data) => {
          if (data.code == 1) {
            let users = data.data;
            users.forEach(function(user) {
              let label = user.user.username;
              if (user.user) {
                label = user.user.username + '(' + user.user.nickname + ')';
              }
              user.label = label;
              user.expGroupName = group.name;
            });
            this.allUsers = users;
            resolve();
          } else {
          }
        });
      });
    },
    // 穿梭框过滤回调
    filterMethod(data, query) {
      return data.label.indexOf(query.trim()) > -1;
    },
    // 穿梭框数据有变化
    handleChange(targetKeys, direction, moveKeys) {
      if (direction === 'right') {
        //添加
        this.selectedUsers = this.selectedUsers.concat(
          moveKeys.map((id) => {
            return this.allUsers.find((user) => user.userId === id);
          })
        );
      } else {
        //移除
        moveKeys.forEach((id) => {
          this.removeUser(id);
        });
      }
    },
    confirmSelect() {
      this.group.userList = this.selectedUsers;
      this.closeModal();
    },
    // 移除指定用户
    removeUser(userId) {
      let index = this.selectedUsers.findIndex((user) => user.userId === userId);
      this.selectedUsers.splice(index, 1);
    },
    // 清空用户，直接接入空数据
    clearUsers() {
      this.selectedUsers = [];
    },
    // 穿梭框渲染回调
    render2(user) {
      return user.label + '<span style="float:right">' + user.des + '</span>';
    }
  }
};
</script>

<style scoped>
.demo-spin-icon-load {
  animation: ani-demo-spin 1s linear infinite;
}
@keyframes ani-demo-spin {
  from {
    transform: rotate(0deg);
  }
  50% {
    transform: rotate(180deg);
  }
  to {
    transform: rotate(360deg);
  }
}
.demo-spin-col {
  height: 200px;
  position: relative;
  border: 1px solid #eee;
}

.experimental-group {
  width: 150px;
}
.experimental-group >>> .ivu-select-selection {
  border-radius: 15px;
  border: 1px solid #cccccc !important;
  outline: 0;
}
.experimental-group >>> .ivu-select-selection:hover {
  border: 1px solid #1563C2  !important;
  box-shadow: 0px 0px 8px #1563C2 ;
}
.experimental-group >>> .ivu-select-selection:hover i {
  color: #1563C2 ;
}
</style>
